import argparse
import time

TT_SEC = 10

class HueScript(object):
    def __init__(self, time_dilation=1, debug=False):
        self.eventdict = {}
        self.last_idx = 0

        if time_dilation <= 0:
            time_dilation = 1

        self.time_dilation = time_dilation
        self.debug = debug

        self._setUpArgParser()
        self._parseArgs()

    def _setUpArgParser(self):
        self.parser = argparse.ArgumentParser()
        self.parser.add_argument('--debug', '-d', action='store_true',
                help='Enable debug output.')
        self.parser.add_argument('--logLocation', '-o',
                help='Location to log cues.', metavar='FILE')
        self.parser.add_argument('--timeDilation', default=1, type=float,
                help='Scale factor for transitions and script speed.', metavar='SECS')

    def _parseArgs(self):
        self.args = self.parser.parse_args()

        self.debug |= self.args.debug
        self.time_dilation = self.args.timeDilation

    # This needs to be implemented by a descendant.
    def generateCues(self):
        pass

    def register(self, idx, function, args=[], kwargs={}, relative=True):

        if not isinstance(args, list):
            args = [args]

        if relative:
            idx += self.last_idx
            self.last_idx = idx

        idx /= self.time_dilation
        idx = int(idx)

        try: 
            kwargs['transitiontime'] /= self.time_dilation
            kwargs['transitiontime'] = int( kwargs['transitiontime'] )
        except KeyError:
            pass

        try:
            kwargs['data']['transitiontime'] /= self.time_dilation
            kwargs['data']['transitiontime'] = int( kwargs['data']['transitiontime'] )
        except KeyError:
            pass

        if self.eventdict.has_key(idx):
            self.eventdict[idx].append( (function, args, kwargs) )
        else:
            self.eventdict[idx] = [(function, args, kwargs)]

    def execute(self):
        if self.debug:
            print self.args.__dict__
            print self.getCueListStr()

        max_idx = max([int(k) for k in self.eventdict.keys()])

        if self.debug:
            print max_idx

        for i in range(0, max_idx + 1):

            if self.debug:
                print i

            if self.eventdict.has_key(i):
                for func, args, kwargs in self.eventdict[i]:

                    if self.debug:
                        print func, args, kwargs

                    r = func(*args, **kwargs)

                    if self.debug:
                        for key, val in r.iteritems():
                            print key, val, val.json

            time.sleep(1)

    def getCueListStr(self):
        s = ''
        lineTemplate = '%s, %s, %s, %s\n'

        for key in sorted(self.eventdict.keys(), key=int):
            for tuple_ in self.eventdict[key]:
                func, args, kwargs = map(str, tuple_)
                s += lineTemplate % (str(key), func, args, kwargs)

        return s

    def writeLog(self, s):
        if self.args.logLocation:
            with open(self.args.logLocation, 'wb') as f:
                f.write(s)
            return True
        return False
